import React, {Component} from 'react';
import {Breadcrumb, Button, Form, message, Input, Upload} from "antd";
import {NavLink} from "react-router-dom";
import {PlusOutlined, DeleteOutlined} from '@ant-design/icons';
import axios from "axios";
const instance = axios.create({
    withCredentials:true  //表示跨域请求时是否需要使用凭证，默认为false
})
instance.defaults.baseURL = 'http://localhost:3000';
instance.defaults.headers.post['Content-Type'] = 'multipart/form-data; charset=UTF-8';

class Carousel extends Component {
    state = {
        carousel: [],
    }
    changeCarousel = async (id) => {
        if (
            this.state.carousel[id].carousel_img !== "" &&
            this.state.carousel[id].carousel_url !== "" &&
            this.state.carousel[id].carousel_title !== ""
        ) {
            let result = await this.$axios.post("/admin/changecarousel", this.state.carousel[id]);
            if (result.data.state.type === "SUCCESS") {
                this.state.carousel[id].carousel_id !== "" &&
                message.success("修改成功");
                this.state.carousel[id].carousel_id === "" &&
                message.success("添加成功");
                this.carouselList();
            }
        } else {
            message.error("请上传图片/输入地址或标题")
        }
    }
    del = (id) => {
        if (
            this.state.carousel[id].carousel_img !== "" &&
            this.state.carousel[id].carousel_url !== "" &&
            this.state.carousel[id].carousel_id !== "" &&
            this.state.carousel[id].carousel_title !== ""
        ) this.deleteCarousel(id);
        else {
            let carousel = this.state.carousel;
            if(carousel[id].carousel_id === ""){
                carousel.shift();
                this.setState({carousel: carousel});
            }
        }
    }
    handleInputChange1 = (e,id) =>{
        let carousel = this.state.carousel;
        carousel[id].carousel_title = e.target.value;
        this.setState({carousel: carousel});
    }
    handleInputChange2 = (e,id) =>{
        let carousel = this.state.carousel;
        carousel[id].carousel_url = e.target.value;
        this.setState({carousel: carousel});
    }
    add = () => {
        let carousel = this.state.carousel;
        carousel.unshift({
            carousel_img: "",
            carousel_url: "",
            carousel_id: "",
            carousel_title: ""
        });
        this.setState({carousel: carousel});
    }
    //文件上传成功时的钩子
    handleChange = (file, id) => {
        console.log(file);
        if (file.response){
            let carousel = this.state.carousel;
            carousel[id].carousel_img = file.response.url;
            this.setState({carousel: carousel});
        }
        if (
            this.state.carousel[id].carousel_url !== "" &&
            this.state.carousel[id].carousel_title !== ""
        )
            this.changeCarousel(id);
    }
    deleteCarousel = async (id) => {
        let result = await this.$axios.post("/admin/deletecarouse", this.state.carousel[id]);
        if (result.data.state.type === "SUCCESS") {
            message.success("删除成功");
            this.carouselList();
        }
    }
    carouselList = async () => {
        let result = await this.$axios.post("/admin/carousellist", { lable_name: "" });
        if (result.data.state.type === "SUCCESS") {
            this.setState({carousel: result.data.data});
        }
    }
    componentDidMount() {
        this.carouselList();
    }
    customRequest = async (options,id)=>{
        let params = new FormData();
        params.append("file", options.file);
        instance.post(`/uploads`, params).then((res)=>{
            let carousel = this.state.carousel;
            carousel[id].carousel_img = res.data.url;
            this.setState({carousel: carousel});
        })
    }

    render() {
        const {carousel} = this.state;
        const uploadButton = (
            <div>
                <PlusOutlined />
                <div className="ant-upload-text">Upload</div>
            </div>
        );
        return (
            <div>
                <div className="top">
                    <Breadcrumb>
                        <Breadcrumb.Item>
                            <NavLink to='/'>首页</NavLink>
                        </Breadcrumb.Item>
                        <Breadcrumb.Item>
                            网站管理
                        </Breadcrumb.Item>
                        <Breadcrumb.Item>
                            轮播图管理
                        </Breadcrumb.Item>
                    </Breadcrumb>
                </div>
                <div className="main" style={{paddingTop:"20px"}}>
                    <Button type="primary" shape="circle" onClick={this.add} icon={<PlusOutlined />} />
                    <span style={{color:"red",marginLeft:"50px"}}>
                        温馨提示：
                        填写完毕后按回车保存，如果上传图片前其相应的链接不为空，则自动完成相应的添加或修改动作
                    </span>
                </div>
                {
                    carousel.map((carousel,id)=>{
                        return (
                            <div className="main" key={id}>
                                <Form style={{marginTop: "40px", width: "80%"}}>
                                    <Form.Item label={"图片"}>
                                        <Upload
                                            accept="multipart/form-data"
                                            name="avatar"
                                            listType="picture-card"
                                            className="avatar-uploader"
                                            /*action={this.$axios.default.baseURL+"uploads"}*/
                                            showUploadList={false}
                                            customRequest={(option)=>this.customRequest(option,id)}
                                        >
                                            {carousel.carousel_img ? <img src={carousel.carousel_img} alt="avatar" className="avatar" /> : uploadButton}
                                        </Upload>
                                    </Form.Item>
                                    <Form.Item label="标题">
                                        <Input
                                            type="text"
                                            value={carousel.carousel_title}
                                            onChange={(e)=>this.handleInputChange1(e,id)}
                                            onPressEnter={() => this.changeCarousel(id)}
                                        />
                                    </Form.Item>
                                    <Form.Item label="链接">
                                        <Input
                                            type="text"
                                            value={carousel.carousel_url}
                                            onChange={(e)=>this.handleInputChange2(e,id)}
                                            onPressEnter={() => this.changeCarousel(id)}
                                        />
                                    </Form.Item>
                                    <Button type="primary" shape="circle" onClick={()=>this.del(id)} icon={<DeleteOutlined />} className="del"></Button>
                                </Form>
                            </div>
                        )
                    })
                }
            </div>
        );
    }
}

export default Carousel;
